from datetime import datetime

from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.mixins import UpdateModelMixin
from rest_framework_jwt.settings import api_settings
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.response import Response
from rest_framework_jwt.views import ObtainJSONWebToken
from apps.carts.utils import merge_cart_cookie_to_redis

from apps.goods.models import SKU

from apps.users.models import User, Address
from apps.users.serializers import (
    CreateUserSerializer,
    UserDetailSerializer,
    EmailSerializer,
    UserAddressSerializer,
    AddressTitleSerializer,
    UserBrowserSerializer,
    SKUSerializer,
)
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import GenericViewSet


class UserView(CreateAPIView):
    """用户注册视图"""

    serializer_class = CreateUserSerializer


class UserCountView(APIView):
    """校验用户名是否已注册"""

    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        data = {"username": username, "count": count}
        return Response(data)


class MobileCountView(APIView):
    """校验用户名是否已注册"""

    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        data = {"mobile": mobile, "count": count}
        return Response(data)


class UserDetailView(RetrieveAPIView):
    """用户详细信息展示"""

    serializer_class = UserDetailSerializer
    # queryset = User.objects.all() # 减少数据库的查询，直接使用self.request.user
    permission_classes = [IsAuthenticated]  # 指定权限，只有通过认证的用户才能访问

    def get_object(self):
        """重写父类方法"""
        return self.request.user


class EmailView(UpdateAPIView):
    """更新用户邮箱"""

    serializer_class = EmailSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


class EmailVerifyView(APIView):
    """邮箱激活"""

    def get(self, request):
        # 获取前端查询字符串中传入的token
        token = request.query_params.get("token")
        if not token:
            return Response({"message": "缺少token"}, status=status.HTTP_400_BAD_REQUEST)
        # 把token解密并查询对应的user
        user = User.check_verify_email_token(token)
        if user is None:
            return Response({"message": "激活失败"}, status=status.HTTP_400_BAD_REQUEST)
        # 修改当前User的email_active为True
        user.email_active = True
        user.save()
        return Response({"message": "ok"})


class AddressViewSet(UpdateModelMixin, GenericViewSet):
    """用户收货地址新增"""

    permission_classes = [IsAuthenticated]
    serializer_class = UserAddressSerializer

    # queryset = ''

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def create(self, request):
        """用户新增地址有上限，最多只能增加20个收货地址"""
        user = request.user
        # adders_count = user.addresses.all().count()
        adders_count = Address.objects.filter(user=user).count()
        if adders_count >= 20:
            return Response(
                {"message": "最多只能增加20个收货地址"}, status=status.HTTP_400_BAD_REQUEST
            )
        serializer = self.get_serializer(
            data=request.data
        )  # ,context=request context可以传到序列化器中，在序列化器使用
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    # GET /addresses/
    def list(self, request, *args, **kwargs):
        """
        用户地址列表数据
        """
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response(
            {
                "user_id": user.id,
                "default_address_id": user.default_address_id,
                "limit": 20,
                "addresses": serializer.data,
            }
        )

    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    @action(
        methods=["put"], detail=True
    )  # detail 是否加pk,地址/user/addresses/1/title/ 可以指定请求方式和是否添加pk
    def title(self, request, pk=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

    # put /addresses/pk/status/
    @action(methods=["put"], detail=True)
    def status(self, request, pk=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({"message": "OK"}, status=status.HTTP_200_OK)


class UserBrowserHistoryView(CreateAPIView):
    """添加用户浏览商品记录"""

    serializer_class = UserBrowserSerializer
    permission_class = [IsAuthenticated]  # 指定权限

    def get(self, request):
        """查询浏览记录"""
        # 创建redis链接对象
        redis_conn = get_redis_connection("history")
        # 获取redis当前用户的浏览记录
        user = request.user
        sku_ids = redis_conn.lrange("history_%d" % user.id, 0, -1)
        # 把sku_id对应的sku模型查询
        # SKU.objects.filter(id__in=sku_ids)
        sku_list = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            sku_list.append(sku)
        # 序列化
        serializer = SKUSerializer(instance=sku_list, many=True)
        # 返回
        return Response(serializer.data)


jwt_response_payload_handler = api_settings.JWT_RESPONSE_PAYLOAD_HANDLER


class UserAuthorizeView(ObtainJSONWebToken):
    """自定义账号密码登录视图,实现购物车登录合并"""

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            user = serializer.object.get("user") or request.user
            token = serializer.object.get("token")
            response_data = jwt_response_payload_handler(token, user, request)
            response = Response(response_data)
            if api_settings.JWT_AUTH_COOKIE:
                expiration = datetime.utcnow() + api_settings.JWT_EXPIRATION_DELTA
                response.set_cookie(
                    api_settings.JWT_AUTH_COOKIE,
                    token,
                    expires=expiration,
                    httponly=True,
                )
            # 账号登录时合并购物车
            merge_cart_cookie_to_redis(request, user, response)
            return response
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
